﻿/**************************************************************
 *
 * 命名空间：Sgr.DataCategories.Application.Commands.AdministrativeDivisions
 * 创建时间：2025/3/19
 * 描述：删除行政区划命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.DataCategories.Domain.AdministrativeDivisions;
using Sgr.Domain.Uow;
using Sgr.Exceptions;
using Sgr.Modules;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace Sgr.DataCategories.Application.Commands.AdministrativeDivisions
{
    /// <summary>
    /// 删除行政区划命令处理器
    /// </summary>
    public class DeleteAdministrativeDivisionCommandHandler
        : IRequestHandler<DeleteAdministrativeDivisionCommand, CommandResult<bool>>
    {
        private readonly IAdministrativeDivisionManage _administrativeDivisionManage;
        private readonly IAdministrativeDivisionRepository _administrativeRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="administrativeDivisionManage">行政区划管理器</param>
        /// <param name="administrativeRepository">行政区划仓储</param>
        public DeleteAdministrativeDivisionCommandHandler(
            IAdministrativeDivisionManage administrativeDivisionManage, IAdministrativeDivisionRepository administrativeRepository)
        {
            _administrativeDivisionManage = administrativeDivisionManage;
            _administrativeRepository = administrativeRepository;
        }

        /// <summary>
        /// 处理删除行政区划命令
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(
            DeleteAdministrativeDivisionCommand request,
            CancellationToken cancellationToken)
        {
            // 查找部门实体
            var entity = await _administrativeRepository.GetAsync(request.Id, cancellationToken);

            // 如果找不到部门，返回NotFound结果
            if (entity == null)
                return CommandResult.NotFound<bool>("未找到指定的行政区划");

            // 提交事务
            bool result = await _administrativeDivisionManage.RemoveNodeAsync(request.Id, request.IsCascade, cancellationToken);

            // 验证保存结果
            if (!result)
                return CommandResult.Error<bool>("删除行政区划过程中发生错误");

            // 返回成功结果
            return CommandResult.Success(true, "行政区划删除成功");
        }
    }
}